<?php

/**
 * Vega Framework
 * 
 * @url http://vega.com.vn
 * @url http://clip.vn
 */

/**
 * Vega_Db
 * 
 * Static foudation class
 *
 */

class Vega_Db
{
    const MASTER = 'master';
    
    const SLAVE = 'slave';
    
    protected static $_registry = array();
    
    /**
     * Init a Vega_Db_Abstract
     *
     * @param string $name 
     * @param drive $drive
     * @param array $masterConfig
     * @param array $slaveConfig
     * @return Vega_Db_Abstract
     */
    public static function initDb($name, $drive, $masterConfig, $slaveConfig = null) 
    {
        $className = self::loadDbClass($drive);
        
        $db = new $className($masterConfig, $slaveConfig);
        
        self::$_registry[$name] = $db;
        return $db;
    }
    
    /**
     * Get database connection object from registry
     *
     * @param string $name
     * @return Vega_Db_Abstract
     */
    public static function getDb($name)
    {
        if (isset(self::$_registry[$name]))
        {
            return self::$_registry[$name];
        }
        
        require_once 'Vega/Db/Exception.php';
        throw new Vega_Db_Exception('Database object does not exist');
    }
    
    /**
     * Load a Vega_Db_Abstract class.
     *
     * @param string $drive Driver name.
     * @return Vega_Db_Abstract
     */
    public static function loadDbClass($drive)
    {
        $drive = ucfirst(strtolower($drive));
        
        $classPath = 'Vega/Db/' . $drive . '.php';
        
        @require_once $classPath;
        
        $className = 'Vega_Db_' . $drive;
        
        if (!class_exists($className))
        {
            throw new Vega_Db_Exception('Could not load database class');
        }
        return $className;
    }
}
